using System;
using System.Collections.Generic;
using System.Linq;
using VoiceAd.Models;
using System.Web.Security;

namespace VoiceAd.DAL
{
    public class CustomerRepository : ICustomerRepository, IDisposable
    {
        private dbVoiceAdDataContext context = new dbVoiceAdDataContext();

        public CustomerRepository(dbVoiceAdDataContext db)
        {
            this.context = db;
        }

        public IEnumerable<tblCustomer> GetListCustomers()
        {
            return context.tblCustomers.ToList();
        }

        public tblCustomer GetCustomerById(int id)
        {
            return context.tblCustomers.Where(x => x.Id == id).FirstOrDefault();
        }

        public tblCustomer GetCustomerByName()
        {
            string strUser = Membership.GetUser().UserName;
            return context.tblCustomers.Where(x => x.UserName == strUser).FirstOrDefault();
        }

        public void InsCustomer(tblCustomer tblcustomer)
        {
            context.tblCustomers.InsertOnSubmit(tblcustomer);
            context.SubmitChanges();
        }

        public void UpdCustomer(tblCustomer tblcustomer)
        {
            tblCustomer obj = context.tblCustomers.Where(x => x.Id == tblcustomer.Id).First();
            obj.UserName = tblcustomer.UserName;
            obj.CompanyName = tblcustomer.CompanyName;
            obj.Address = tblcustomer.Address;
            obj.Telephone = tblcustomer.Telephone;
            obj.Fax = tblcustomer.Fax;
            obj.UserId = tblcustomer.UserId;
            context.SubmitChanges();
        }

        public void DelCustomer(int id)
        {
            tblCustomer obj = context.tblCustomers.Single(x => x.Id == id);
            context.tblCustomers.DeleteOnSubmit(obj);
            context.SubmitChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
